package com.smart.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * <p><b>Description:</b>  实例化对象
 * <p><b>Company:</b>
 *
 * @author created by Jesse Xu at 14:05 on 2019/9/23
 * @version V0.1
 * @classNmae ReflectionUtil
 */
public final class ReflectionUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReflectionUtil.class);

    /**
     * 创建实例
     * @param cls
     * @return
     */
    public static Object newInstance(Class<?> cls){
    Object instance = null;
        try {
            instance  = cls.newInstance();
        } catch (Exception e) {
            LOGGER.error("new instance failure ",e);
            throw new RuntimeException(e);
        }
        return instance;
    }

    public static Object invokeMethod(Object obj, Method method,Object... arg){
        Object result = null;
        try {
            method.setAccessible(true);
            result =method.invoke(obj,arg);
        } catch (Exception e) {
            LOGGER.error("invoke method failure ",e);
            throw new RuntimeException(e);
        }
        return result;
    }

    public static void setField(Object obj, Field field,Object value){
        try {
            field.setAccessible(true);
            field.set(obj,value);
        } catch (Exception e) {
            LOGGER.error("set value failure ",e);
            throw new RuntimeException(e);
        }
    }

}
